package com.grm.util;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * desc: rabbitmq工具类
 *
 * @author gaorimao
 * @since 2021-3-25
 */
public class RabbitMqUtils {
	private static ConnectionFactory factory;

	static {
		factory = new ConnectionFactory();
		factory.setHost("127.0.0.1");
		//amqp port=5672,web port=15672
		factory.setPort(5672);
		factory.setVirtualHost("/ems");
		factory.setUsername("ems");
		factory.setPassword("ems");
	}

	/**
	 * desc: 获取RabbitMQ的连接
	 */
	public static Connection getConnection() {
		Connection connection = null;
		try {
			connection = factory.newConnection();
		} catch (IOException | TimeoutException e) {
			e.printStackTrace();
		}
		return connection;
	}

	/**
	 * desc: 一般消费者不用关闭连接 只用于生产者关闭连接
	 */
	public static void close(Channel channel, Connection connection) {
		try {
			if (channel != null) {
				channel.close();
			}
			if (connection != null) {
				connection.close();
			}
		} catch (IOException | TimeoutException e) {
			e.printStackTrace();
		}
	}
}
